﻿using System;
using UnityEngine;
using UnityEngine.UI;

public class EditIconUI : MonoBehaviour
{
    public GameObject nextBtn;
    public GameObject loadImgObj;

    public RawImage iconImg;
    float iconSize;

    Tex m_Tex;

    public Action<Tex> onEditEnd;

    public static int maxSize = 2048;

    Texture2D texture;

    void Start()
    {
        nextBtn.gameObject.SetActive(false);
        loadImgObj.gameObject.SetActive(true);

        iconSize = iconImg.rectTransform.rect.height;
    }

    public void OnClickLoadImage()
    {
        EditPhotoItem.LoadImg((newtexture) =>
        {
            OnLoadImageEnd(newtexture);
        });
    }

    Texture2D m_Texture;
    void OnLoadImageEnd(Texture2D texture)
    { 
        m_Tex = new Tex(texture.EncodeToJPG(80),texture.width, texture.height);

        iconImg.gameObject.SetActive(true);

        if (m_Texture)
            DestroyImmediate(m_Texture);
        m_Texture = texture;

        UnityFunctions.SetRawImage(iconImg, texture, iconSize);
        //iconImg.texture = texture;// UnityFunctions.GetSpriteWithByte(m_Tex.texWidth, m_Tex.texHeight, m_Tex.tex);

        nextBtn.gameObject.SetActive(true);
        loadImgObj.gameObject.SetActive(false);
    }

    public void OnClickNext()
    {
        onEditEnd?.Invoke(m_Tex);
    }

    public void OnClickSkip()
    {
        onEditEnd?.Invoke(null);
    }

    void OnDestroy()
    {
        if (m_Texture)
            DestroyImmediate(m_Texture);
        //if (texture != null)
        //    Destroy(texture);

       // NewTextureController.instance.OnDestroyTex(texture);
    }
}
